package com.lipi.mall.ware.service.impl;

import com.lipi.common.constant.WareConstant;
import com.lipi.mall.ware.entity.PurchaseDetailEntity;
import com.lipi.mall.ware.service.PurchaseDetailService;
import com.lipi.mall.ware.service.WareSkuService;
import com.lipi.mall.ware.vo.MergeVO;
import com.lipi.mall.ware.vo.PurchaseDoneVO;
import com.lipi.mall.ware.vo.PurchaseItemDoneVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lipi.common.utils.PageUtils;
import com.lipi.common.utils.Query;

import com.lipi.mall.ware.dao.PurchaseDao;
import com.lipi.mall.ware.entity.PurchaseEntity;
import com.lipi.mall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {


    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();

        wrapper.eq("status", 0).or().eq("status", 1);

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MergeVO vo) {

        //如果没有传输purchaseID,新建采购单并合并
        Long purchaseId = vo.getPurchaseId();
        if (purchaseId == null) {
            //新建采购单
            PurchaseEntity purchaseEntity = new PurchaseEntity();

            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATE.getCode());

            this.baseMapper.insert(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        //合并采购需求到采购单
        List<Long> items = vo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = items.stream()
                .map(item -> {
                    PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();

                    detailEntity.setId(item);
                    detailEntity.setPurchaseId(finalPurchaseId);
                    detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
                    return detailEntity;
                })
                .collect(Collectors.toList());

        purchaseDetailService.updateBatchById(collect);

        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());

        this.baseMapper.updateById(purchaseEntity);
    }

    @Override
    public void received(List<Long> ids) {
        //1、确认当前采购单是新建或者已分配状态
        List<PurchaseEntity> collect = ids.stream()
                .map(id -> {
                    PurchaseEntity purchaseEntity = this.baseMapper.selectById(id);
                    return purchaseEntity;
                }).filter(
                        entity -> {
                            if (entity.getStatus() == WareConstant.PurchaseStatusEnum.CREATE.getCode() ||
                                    entity.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                                return true;
                            }
                            return false;
                        }
                ).map(item -> {
                    item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
                    item.setUpdateTime(new Date());
                    return item;
                })
                .collect(Collectors.toList());
        //2、改变采购单状态

        this.updateBatchById(collect);

        //3、改变采购项状态

        collect.forEach(
                (item -> {
                    List<PurchaseDetailEntity> entities = purchaseDetailService.listDetailByPurchaseId(item.getId());

                    List<PurchaseDetailEntity> collect1 = entities.stream().map(detail -> {
                        PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                        purchaseDetailEntity.setId(detail.getId());
                        purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.RECEIVE.getCode());

                        return purchaseDetailEntity;
                    }).collect(Collectors.toList());

                    purchaseDetailService.updateBatchById(collect1);
                })
        );
    }

    @Transactional
    @Override
    public void done(PurchaseDoneVO vo) {

        //1、改变采购项状态
        //记录采购项中是否存在采购失败的项，若有：false,没有：true
        boolean flag = true;
        List<PurchaseItemDoneVO> items = vo.getItems();

        List<PurchaseDetailEntity> updates = new ArrayList<>();

        for (PurchaseItemDoneVO item : items) {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(item.getItemId());
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROE.getCode()) {
                flag = false;
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.HASERROE.getCode());
            } else {
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                //项采购成功，库存入库
                PurchaseDetailEntity entity = purchaseDetailService.getById(item.getItemId());

                //加库存
                wareSkuService.addStock(entity.getSkuId(), entity.getWareId(), entity.getSkuNum());

            }
            updates.add(detailEntity);
        }
        purchaseDetailService.updateBatchById(updates);

        //2、改变采购单状态：如果所有采购项都成功，采购单就成功，否则采购单状态为存在异常.
        Long purchaseId = vo.getId();
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setStatus(flag ? WareConstant.PurchaseStatusEnum.FINISH.getCode()
                : WareConstant.PurchaseStatusEnum.HASERROE.getCode());

        this.updateById(purchaseEntity);
        //3、库存入库
    }
}